package ms.unicorn.dsl.eistar.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import eistar.Entity;
import eistar.Model;
import eistar.impl.ModelImpl;

public class UnionModel extends ModelImpl {	
	
	public static Model combineModel(Model...models ) {
		Model result = null;
		for (Model m: models)
			if (result == null)
				result = m;
			else if (result instanceof UnionModel)
				((UnionModel) result).combine(m);
			else {
				UnionModel um = new UnionModel();
				um.getRefs().add(result);
				um.getRefs().add(m);
				result = um;
			}
		return result;
	}
	
	@Override
	public <T extends Entity> List<T> getModelElement(Class<? extends T> eClass) {
		List<Model> childModels = getMembers(Model.class);
		Set<T> result = new TreeSet<T>();
		
		for(Model m: childModels) {
			List<T> me = m.getModelElement(eClass);
			result.addAll(me);
		}
		return new ArrayList<T>(result);
	}
	
	public void combine(Model model) {
		if (model instanceof UnionModel)
			for (Model m : model.getMembers(Model.class))
				getRefs().add(m);
		else
			getRefs().add(model);
	}
}
